module.exports = class extends baseLogic {
    constructor() {
        super();
        this.artLabelLogic = this.loadLogic('cms/article-label');
    }

    static init() {
        return new this();
    }

    async getItems(FindFilterModel, curPage, pageSize, sort, moduleId, userInfo) {
        let self = this;
        let Result = {};
        Result.CurPage = curPage;
        Result.PageSize = pageSize;
        let findFilter2 = {};
        let FindFilter = await this.func.degree.getDegree(moduleId, userInfo, {
            createBy: 'Art_UserID',
            orgId: 'Art_OrgID',
            partnersId: 'Art_PartnersID'
        });
        if (FindFilterModel.Art_Title) {
            FindFilter.Art_Title = {
                '$like': '%' + FindFilterModel.Art_Title + '%'
            };
        }

        if (FindFilterModel.Art_IsRecommend !== undefined) {
            FindFilter.Art_IsRecommend = Number(FindFilterModel.Art_IsRecommend);
        }


        if (FindFilterModel.Art_IsHide !== undefined) {
            FindFilter.Art_IsHide = Number(FindFilterModel.Art_IsHide);
        }

        if (FindFilterModel.AR_LabelCode) {
            var selectLabel = await this.artLabelLogic.getItemByID(FindFilterModel.AR_LabelCode);
            if (selectLabel && selectLabel.al_isparent === 1) {
                let ids = [];
                let items = await this.artLabelLogic.getItems({
                    parentIds: `${selectLabel.al_parent_ids}${selectLabel.al_id}`
                });
                items.forEach(it => {
                    ids.push(it.al_id)
                });
                findFilter2.AR_LabelCode = ids;
            } else {
                findFilter2.AR_LabelCode = FindFilterModel.AR_LabelCode;
            }
        }

        if (FindFilterModel.UserCreatetime) {
            FindFilter.UserCreatetime = {
                '$between': FindFilterModel.UserCreatetime.split(',')
            };
        }

        this.DB.cms_article_items.Access.hasMany(this.DB.cms_article_items_label_code.Access, {
            foreignKey: 'AR_ArtID'
        });
        let data = await this.DB.cms_article_items.Access.findAndCountAll({
            attributes: ['Art_CreateTime', 'Art_ReadCount', 'Art_UserID', 'Art_IsRecommend', 'Art_IsPreShowImg', 'Art_IsHide', 'Art_Label', 'Art_Title', 'Art_ID'],
            include: [{
                model: this.DB.cms_article_items_label_code.Access,
                where: findFilter2
            }],
            where: FindFilter,
            order: [
                sort.split('|')
            ],
            group: 'Art_ID',
            offset: (curPage - 1) * pageSize,
            limit: pageSize

        });
        // let data = await this.DB.v_articleitems.Access.findAndCountAll({
        //     attributes: ['Art_CreateTime', 'Art_ReadCount', 'Art_UserID', 'Art_IsRecommend', 'Art_IsPreShowImg', 'Art_IsHide', 'Art_Label', 'Art_Title', 'Art_ID', 'AR_LabelCode'],
        //     where: FindFilter,
        //     order: [
        //         sort.split('|')
        //     ],
        //     group: 'Art_ID',
        //     offset: (curPage - 1) * pageSize,
        //     limit: pageSize
        // });
        Result.RsCount = data.count.length > 0 ? data.count[0].count : 0;
        Result.DataList = JSON.parse(JSON.stringify(data.rows));
        //---------------------解析记录中的分类名称
        let ArtLabelsItems = await this.artLabelLogic.getItemsByDegree(moduleId, userInfo);
        for (let j = 0; j < Result.DataList.length; j++) {
            let item = Result.DataList[j];
            item.Art_CreateTime = this.moment(item.Art_CreateTime).format('YYYY-MM-DD HH:mm');
            item.Art_labelName = [];
            for (let i = 0; i < item.cms_article_items_label_codes.length; i++) {
                let it = item.cms_article_items_label_codes[i];
                let itObj = ArtLabelsItems.find(item => {
                    return item.al_id === Number(it.AR_LabelCode)
                });
                if (itObj) item.Art_labelName.push(itObj.al_name);
            }
            item.Art_labelName = item.Art_labelName.join(',');
        }


        return Result;
    }

    async getItem(id) {

        let model = await this.DB.cms_article_items.Access.findOne({
            where: {
                Art_ID: id
            },
            raw: true
        });
        return model;


    }

    async insertOrUpdate(_model, userInfo) {
        let model = {};
        if (_model.Art_ID && _model.Art_ID !== '') {
            model = await this.getItem(_model.Art_ID);
            if (!model) {
                return false;
            }
        } else {
            model.Art_ID = this.webTools.myuuid.createUUID();
            model.Art_CreateTime = this.moment().format("YYYY-MM-DD HH:mm:ss");
        }
        model.Art_Title = _model.Art_Title;
        model.Art_Label = _model.Art_Label.join(',');
        model.Art_Imgs = _model.Art_Imgs;
        model.Art_SignImg_s = _model.Art_SignImg_s;
        model.Art_SignImg_b = _model.Art_SignImg_b;
        model.Art_Content = _model.Art_Content;
        model.Art_ReadCount = _model.Art_ReadCount || 0;
        model.Art_Intro = _model.Art_Intro || '';
        model.Art_ArticleFrom = _model.Art_ArticleFrom;
        model.Art_UserID = userInfo.UserID;
        model.Art_OrgID = userInfo.UserOrgStructID;
        model.Art_PartnersID = userInfo.UserPartnersID;
        model.Art_VideoPath = _model.Art_VideoPath || '';
        model.Art_IsRecommend = _model.Art_IsRecommend;
        model.Art_IsPreShowImg = _model.Art_IsPreShowImg;
        model.Art_ViewStyle = _model.Art_ViewStyle;
        model.Art_IsHide = _model.Art_IsHide || 0;
        model.Art_Imgs = _model.LastExistImg;
        if (_model.Art_ID && _model.Art_ID !== '') {
            await this.DB.cms_article_items.Access.update(model, {
                where: {
                    Art_ID: _model.Art_ID
                }
            });
            this.DB.cms_article_items_label_code.Access.destroy({
                where: {
                    AR_ArtID: _model.Art_ID
                }
            });
        } else {
            model = await this.DB.cms_article_items.Access.create(model);
        }

        if (model) {
            _model.Art_Label.map(async item => {
                this.DB.cms_article_items_label_code.Access.create({
                    AR_ID: this.webTools.myuuid.createUUID(),
                    AR_LabelCode: item,
                    AR_ArtID: model.Art_ID
                });
            });
            return true;
        }
        return false;
    }

    async del(keys) {
        return await this.DB.cms_article_items.Access.destroy({
            where: {
                Art_ID: keys
            }
        });
    }
};